package cn.com.huzo.service.inventory.impl;

import cn.com.huzo.model.entities.inventory.StockInLinesEntity;
import cn.com.huzo.repository.inventory.StockInLinesPoHeaderRepository;
import cn.com.huzo.repository.inventory.StockInLinesPoLinesRepository;
import huzofw.model.entities.paginator.Paginator;
import cn.com.huzo.repository.inventory.StockInLinesRepository;
import huzofw.service.impl.GenericManagerImpl;
import cn.com.huzo.service.inventory.StockInLinesManager;
import cn.com.huzo.service.inventory.StockInLinesPoLinesManager;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入库单明细数据管理服务类实现。
 *
 * @author 吴旭
 */
@Service("StockInLinesManager")
public class StockInLinesManagerImpl extends GenericManagerImpl<StockInLinesEntity, String>
        implements StockInLinesManager {

    @Resource(name = "StockInLinesRepository")
    private StockInLinesRepository _dao_lines;

    @Resource(name = "StockInLinesPoHeaderRepository")
    private StockInLinesPoHeaderRepository _dao_po_header;

    @Resource(name = "StockInLinesPoLinesRepository")
    private StockInLinesPoLinesRepository _dao_po_lines;

    @Resource(name = "StockInLinesPoLinesManager")
    private StockInLinesPoLinesManager _manager_stockin_lines_po_lines;

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> fetchForPage(Map<String, Object> criterion) throws Exception {
        Map<String, Object> _result = new HashMap();

        Long offset = (long) (MapUtils.getInteger(criterion, "Limit") * (MapUtils.getInteger(criterion, "PageIndex") - 1));
        long total = _dao_lines.fetchForCount(criterion);

        if (total > 0) {
            if (offset >= total) {
                offset = (total - MapUtils.getInteger(criterion, "Limit")) < 0 ? 0 : (total - MapUtils.getInteger(criterion, "Limit"));
            }
            criterion.put("Offset", offset);
            List<StockInLinesEntity> itemList = _dao_lines.fetchForPage(criterion);
            Paginator<StockInLinesEntity> paginator = new Paginator<>(itemList, offset, MapUtils.getInteger(criterion, "Limit"), total);

            _result.put("TotalRecordCount", paginator.getTotal());
            _result.put("TotalPages", paginator.getTotalPages());
            _result.put("PageIndex", paginator.getPageIndex());
            _result.put("DataList", paginator.getItemList());
            _result.put("Success", true);
        } else {
            _result.put("Success", false);
        }

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> update(List<StockInLinesEntity> itemList,
            Integer limit02, Integer pageIndex02, Integer limit03, Integer pageIndex03) throws Exception {
        Map<String, Object> _result = new HashMap();

        // 第一步，更新入库单明细
        for (int i = 0; i < itemList.size(); i++) {
            _dao_lines.update(itemList.get(i));
        }
        // 第二步，更新每款的相应材料入库数
        for (int i = 0; i < itemList.size(); i++) {
            _dao_po_lines.updateStockInQuantity(itemList.get(i));
        }
        for (int i = 0; i < itemList.size(); i++) {
            _dao_po_lines.updateStockInQuantity02(itemList.get(i));
        }
        // 第三步，返回入库单明细
        Map<String, Object> criterion = new HashMap();
        criterion.put("HeaderId", itemList.get(0).getHeaderId());
        criterion.put("Limit", limit03);           // 每页显示行数
        criterion.put("PageIndex", pageIndex03);   // 当前页
        _result.put("LinesList", fetchForPage(criterion));

        // 第四步，返回入库单明细（到货明细）
        criterion.replace("Limit", limit02);
        criterion.replace("PageIndex", pageIndex02);
        _result.put("LinesPoLinesList", _manager_stockin_lines_po_lines.fetchForPage(criterion));

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> delete(Long headerId, String linesId,
            Integer limit02, Integer pageIndex02, Integer limit03, Integer pageIndex03) throws Exception {
        Map<String, Object> _result = new HashMap();

        // 第一步，删除入库单明细(包括无用的引入的订单内容)
        _dao_lines.delete(linesId);

        // 第三步，返回入库单明细
        Map<String, Object> criterion = new HashMap();
        criterion.put("HeaderId", headerId);
        criterion.put("Limit", limit03);           // 每页显示行数
        criterion.put("PageIndex", pageIndex03);   // 当前页
        _result.put("LinesList", fetchForPage(criterion));

        // 第四步，返回入库单明细（到货明细）
        criterion.replace("Limit", limit02);
        criterion.replace("PageIndex", pageIndex02);
        _result.put("LinesPoLinesList", _manager_stockin_lines_po_lines.fetchForPage(criterion));
        _result.put("LinesPoHeaderList", _dao_po_header.fetchByHeaderKey(headerId));

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> clearArrivalAllowed(List<StockInLinesEntity> itemList,
            Integer limit02, Integer pageIndex02, Integer limit03, Integer pageIndex03) throws Exception {
        Map<String, Object> _result = new HashMap();

        // 第一步，清空入库单明细的到货允许
        for (int i = 0; i < itemList.size(); i++) {
            _dao_lines.clearArrivalAllowed(itemList.get(i));
        }
        // 第二步，更新每款的相应材料入库数
        for (int i = 0; i < itemList.size(); i++) {
            _dao_po_lines.updateStockInQuantity(itemList.get(i));
        }
        for (int i = 0; i < itemList.size(); i++) {
            _dao_po_lines.updateStockInQuantity02(itemList.get(i));
        }
        // 第三步，返回入库单明细
        Map<String, Object> criterion = new HashMap();
        criterion.put("HeaderId", itemList.get(0).getHeaderId());
        criterion.put("Limit", limit03);           // 每页显示行数
        criterion.put("PageIndex", pageIndex03);   // 当前页
        _result.put("LinesList", fetchForPage(criterion));

        // 第四步，返回入库单明细（到货明细）
        criterion.replace("Limit", limit02);
        criterion.replace("PageIndex", pageIndex02);
        _result.put("LinesPoLinesList", _manager_stockin_lines_po_lines.fetchForPage(criterion));

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> batchDeleteLines(Long headerId, Long deletedBy,
            Integer limit02, Integer pageIndex02, Integer limit03, Integer pageIndex03,
            List<StockInLinesEntity> itemList) throws Exception {
        Map<String, Object> _result = new HashMap();

        // 第一步：删除明细
        Integer rowsAffected = _dao_lines.batchDelete(itemList);

        if (rowsAffected > 0) {
            // 第二步：删除空引用的调达及补料单
            _dao_lines.delete_for_sync_lines(headerId);
        }
        // 第三步：返回删除后的数据
        Map<String, Object> criterion = new HashMap();
        criterion.put("HeaderId", headerId);
        criterion.put("Limit", limit03);           // 每页显示行数
        criterion.put("PageIndex", pageIndex03);   // 当前页
        _result.put("LinesList", fetchForPage(criterion));

        // 第四步，返回入库单明细（到货明细）
        criterion.replace("Limit", limit02);
        criterion.replace("PageIndex", pageIndex02);
        _result.put("LinesPoLinesList", _manager_stockin_lines_po_lines.fetchForPage(criterion));
        _result.put("LinesPoHeaderList", _dao_po_header.fetchByHeaderKey(headerId));

        _result.put("Success", true);

        return _result;
    }
}
